package com.yupi.springbootinit.statemachine.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.statemachine.core.StateTransitionRecord;
import com.yupi.springbootinit.statemachine.dto.StateTransitionRecordQueryRequest;
import com.yupi.springbootinit.statemachine.service.StateTransitionRecordService;
import com.yupi.springbootinit.statemachine.vo.StateTransitionStatisticsVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 状态转换记录查询和审计Controller
 * 提供状态转换历史查询、统计分析、审计报表等功能
 */
@Slf4j
@RestController
@RequestMapping("/api/statemachine/records")

public class StateTransitionRecordController {
    
    @Resource
    private StateTransitionRecordService stateTransitionRecordService;
    
    /**
     * 分页查询状态转换记录
     */
    @PostMapping("/query")
    @Operation(summary = "分页查询状态转换记录", description = "支持多条件查询和权限过滤")
    public BaseResponse<IPage<StateTransitionRecord>> queryRecords(
            @Valid @RequestBody StateTransitionRecordQueryRequest request,
            HttpServletRequest httpRequest) {
        try {
            // 获取当前用户ID（简化实现，实际应从JWT或Session获取）
            Long userId = getCurrentUserId(httpRequest);
            
            IPage<StateTransitionRecord> result;
            if (userId != null) {
                // 带权限过滤的查询
                result = stateTransitionRecordService.queryRecordsWithPermission(request, userId);
            } else {
                // 无权限过滤的查询（管理员或系统调用）
                result = stateTransitionRecordService.queryRecords(request);
            }
            
            log.debug("查询状态转换记录: 用户ID={}, 查询条件={}, 结果数={}", 
                    userId, request, result.getRecords().size());
            
            return ResultUtils.success(result);
            
        } catch (Exception e) {
            log.error("查询状态转换记录异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询指定实体的状态转换历史
     */
    @GetMapping("/entity/{entityType}/{entityId}")
    @Operation(summary = "查询实体状态转换历史", description = "查询指定实体的完整状态转换历史")
    public BaseResponse<List<StateTransitionRecord>> getEntityHistory(
            @Parameter(description = "实体类型") @PathVariable String entityType,
            @Parameter(description = "实体ID") @PathVariable Long entityId,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            // 检查权限
            if (userId != null && !hasViewPermission(userId, entityType, entityId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看该实体的转换历史");
            }
            
            List<StateTransitionRecord> history = stateTransitionRecordService.getEntityTransitionHistory(entityType, entityId);
            
            log.debug("查询实体状态转换历史: 实体[{}:{}], 用户ID={}, 记录数={}", 
                    entityType, entityId, userId, history.size());
            
            return ResultUtils.success(history);
            
        } catch (Exception e) {
            log.error("查询实体状态转换历史异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 查询实体状态转换链路
     */
    @GetMapping("/chain/{entityType}/{entityId}")
    @Operation(summary = "查询实体状态转换链路", description = "查询实体的成功状态转换链路")
    public BaseResponse<List<StateTransitionRecord>> getEntityTransitionChain(
            @Parameter(description = "实体类型") @PathVariable String entityType,
            @Parameter(description = "实体ID") @PathVariable Long entityId,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            // 检查权限
            if (userId != null && !hasViewPermission(userId, entityType, entityId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看该实体的转换链路");
            }
            
            List<StateTransitionRecord> chain = stateTransitionRecordService.getEntityTransitionChain(entityType, entityId);
            
            log.debug("查询实体状态转换链路: 实体[{}:{}], 用户ID={}, 链路长度={}", 
                    entityType, entityId, userId, chain.size());
            
            return ResultUtils.success(chain);
            
        } catch (Exception e) {
            log.error("查询实体状态转换链路异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取状态转换统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取状态转换统计", description = "获取指定条件下的状态转换统计信息")
    public BaseResponse<StateTransitionStatisticsVO> getTransitionStatistics(
            @Parameter(description = "实体类型") @RequestParam(required = false) String entityType,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            // 检查统计权限（简化实现，实际应根据角色判断）
            if (userId != null && !hasStatisticsPermission(userId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看统计信息");
            }
            
            StateTransitionStatisticsVO statistics = stateTransitionRecordService.getTransitionStatistics(
                    entityType, startTime, endTime);
            
            log.debug("获取状态转换统计: 实体类型={}, 时间范围=[{} - {}], 用户ID={}", 
                    entityType, startTime, endTime, userId);
            
            return ResultUtils.success(statistics);
            
        } catch (Exception e) {
            log.error("获取状态转换统计异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取转换频次统计
     */
    @GetMapping("/frequency-stats")
    @Operation(summary = "获取转换频次统计", description = "获取各种状态转换的频次统计")
    public BaseResponse<List<Map<String, Object>>> getTransitionFrequencyStats(
            @Parameter(description = "实体类型") @RequestParam(required = false) String entityType,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            if (userId != null && !hasStatisticsPermission(userId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看统计信息");
            }
            
            List<Map<String, Object>> stats = stateTransitionRecordService.getTransitionFrequencyStats(
                    entityType, startTime, endTime);
            
            log.debug("获取转换频次统计: 实体类型={}, 统计项数={}", entityType, stats.size());
            
            return ResultUtils.success(stats);
            
        } catch (Exception e) {
            log.error("获取转换频次统计异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取转换耗时分析
     */
    @GetMapping("/duration-analysis")
    @Operation(summary = "获取转换耗时分析", description = "获取各种状态转换的耗时分析")
    public BaseResponse<List<Map<String, Object>>> getTransitionDurationAnalysis(
            @Parameter(description = "实体类型") @RequestParam(required = false) String entityType,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            if (userId != null && !hasStatisticsPermission(userId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看统计信息");
            }
            
            List<Map<String, Object>> analysis = stateTransitionRecordService.getTransitionDurationAnalysis(
                    entityType, startTime, endTime);
            
            log.debug("获取转换耗时分析: 实体类型={}, 分析项数={}", entityType, analysis.size());
            
            return ResultUtils.success(analysis);
            
        } catch (Exception e) {
            log.error("获取转换耗时分析异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取分析失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取异常转换记录
     */
    @GetMapping("/failed-transitions")
    @Operation(summary = "获取异常转换记录", description = "获取失败的状态转换记录")
    public BaseResponse<List<StateTransitionRecord>> getFailedTransitions(
            @Parameter(description = "实体类型") @RequestParam(required = false) String entityType,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "100") Integer limit,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            if (userId != null && !hasStatisticsPermission(userId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看异常记录");
            }
            
            List<StateTransitionRecord> failedTransitions = stateTransitionRecordService.getFailedTransitions(
                    entityType, startTime, endTime, limit);
            
            log.debug("获取异常转换记录: 实体类型={}, 记录数={}", entityType, failedTransitions.size());
            
            return ResultUtils.success(failedTransitions);
            
        } catch (Exception e) {
            log.error("获取异常转换记录异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取操作人转换统计
     */
    @GetMapping("/operator-stats")
    @Operation(summary = "获取操作人转换统计", description = "获取各操作人的状态转换统计")
    public BaseResponse<List<Map<String, Object>>> getOperatorTransitionStats(
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            if (userId != null && !hasStatisticsPermission(userId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看操作人统计");
            }
            
            List<Map<String, Object>> stats = stateTransitionRecordService.getOperatorTransitionStats(
                    startTime, endTime);
            
            log.debug("获取操作人转换统计: 统计项数={}", stats.size());
            
            return ResultUtils.success(stats);
            
        } catch (Exception e) {
            log.error("获取操作人转换统计异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取慢转换记录
     */
    @GetMapping("/slow-transitions")
    @Operation(summary = "获取慢转换记录", description = "获取耗时超过阈值的状态转换记录")
    public BaseResponse<List<StateTransitionRecord>> getSlowTransitions(
            @Parameter(description = "耗时阈值(毫秒)") @RequestParam(defaultValue = "5000") Long thresholdMs,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "50") Integer limit,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            if (userId != null && !hasStatisticsPermission(userId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限查看慢转换记录");
            }
            
            List<StateTransitionRecord> slowTransitions = stateTransitionRecordService.getSlowTransitions(
                    thresholdMs, limit);
            
            log.debug("获取慢转换记录: 阈值={}ms, 记录数={}", thresholdMs, slowTransitions.size());
            
            return ResultUtils.success(slowTransitions);
            
        } catch (Exception e) {
            log.error("获取慢转换记录异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "获取失败: " + e.getMessage());
        }
    }
    
    /**
     * 导出状态转换记录
     */
    @PostMapping("/export")
    @Operation(summary = "导出状态转换记录", description = "导出符合条件的状态转换记录")
    public BaseResponse<List<StateTransitionRecord>> exportRecords(
            @Valid @RequestBody StateTransitionRecordQueryRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getCurrentUserId(httpRequest);
            
            if (userId == null) {
                return ResultUtils.error(ErrorCode.NOT_LOGIN_ERROR, "请先登录");
            }
            
            // 检查导出权限
            if (!hasExportPermission(userId)) {
                return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "无权限导出记录");
            }
            
            List<StateTransitionRecord> records = stateTransitionRecordService.exportRecords(request, userId);
            
            log.info("导出状态转换记录: 用户ID={}, 导出数量={}", userId, records.size());
            
            return ResultUtils.success(records);
            
        } catch (Exception e) {
            log.error("导出状态转换记录异常", e);
            return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "导出失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户ID（简化实现）
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        // TODO: 实际实现应该从JWT token或Session中获取用户ID
        String userIdHeader = request.getHeader("X-User-Id");
        if (userIdHeader != null && !userIdHeader.isEmpty()) {
            try {
                return Long.parseLong(userIdHeader);
            } catch (NumberFormatException e) {
                log.warn("无效的用户ID格式: {}", userIdHeader);
            }
        }
        return null;
    }
    
    /**
     * 检查查看权限
     */
    private boolean hasViewPermission(Long userId, String entityType, Long entityId) {
        // TODO: 实际实现应该调用权限管理器
        return stateTransitionRecordService.hasPermissionToViewRecord(userId, 
                new StateTransitionRecord() {{
                    setEntityType(entityType);
                    setEntityId(entityId);
                }});
    }
    
    /**
     * 检查统计权限
     */
    private boolean hasStatisticsPermission(Long userId) {
        // TODO: 实际实现应该检查用户角色和权限
        // 简化实现：假设管理员和PMC有统计权限
        return true; // 暂时允许所有用户查看统计
    }
    
    /**
     * 检查导出权限
     */
    private boolean hasExportPermission(Long userId) {
        // TODO: 实际实现应该检查用户角色和权限
        // 简化实现：假设管理员有导出权限
        return true; // 暂时允许所有用户导出
    }
}